var socket;

var student = null;

var loadLayer = null;

var flashId = null;

//指纹图像获取成功
var getImageFlag = false;

//当前无可用设备
if ($("#portList").children().length <= 0){
    $("#openDevice").attr('disabled',"disabled");
    $("#closeDevice").attr('disabled',"disabled");
    $("#checkin").attr('disabled',"disabled");
}
//查看设备开启状态
var deviceIsOpen = sessionStorage.key("deviceIsOpen");


$(function () {
    //根据设备开启状态设置按钮点击
    if (deviceIsOpen != null){
        if (deviceIsOpen === "open"){
            $("#openDevice").removeAttr('disabled',"disabled");
            $("#closeDevice").attr('disabled',"disabled");
            $("#checkin").attr('disabled',"disabled");
        }else{
            $("#openDevice").attr('disabled',"disabled");
            $("#closeDevice").removeAttr('disabled',"disabled");
            $("#checkin").removeAttr('disabled',"disabled");
        }
    }

    /*加载签到列表*/
    $.ajax({
        type: 'get',
        url: 'http://localhost/api/finger/ongoing/checkins',
        success:function (result) {
            var data = result.data;
            for (let i = 0; i <data.length; i++) {
                $("#checkinList").append(
                    '<option value="'+data[i].id+'">'+data[i].course.name+' '+data[i].teacher.name+'</option>'
                )
                if (i == 0){
                    $("#checkinList").val(data[i].id);
                    //加载学生名单
                    initStudentList(data[i].id);
                }
            }
        },
        error:function (result) {
            console.log(result.msg);
        }
    });

    /*设置选择签到加载学生名单*/
    $("#checkinList").change(function () {
        initStudentList($("#checkinList").val());
    });

    /*构建WebSocket*/
    if (typeof (WebSocket) == "undefined"){
        console.log("您的浏览器不支持WebSocket")
    }
    else{
        console.log("您的浏览器支持WebSocket")
        var socketUrl = 'ws://localhost:8082/fingerprint/api/websocket'

        if (socket != null){
            socket.close();
            socket = null;
        }
        socket = new WebSocket(socketUrl);

        //打开事件
        socket.onopen = function (){
        }
        //获取消息事件
        socket.onmessage = function (msg) {
            addMsg(msg.data)
        }
        //关闭事件
        socket.onclose = function() {
            console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function() {
            console.log("websocket发生了错误");
        }
    }

    /*打开设备*/
    $("#openDevice").click(function () {
        openLoadLayer('正在打开设备......');
        var portName = $("#portList").val();
        var options = {
            type: 'get',
            url: 'opt/port/open/'+portName,
            success:function (result) {
                addMsg(result.msg)
                //成功打开串口
                if (result.code === 0){
                    deviceIsOpen = "open";
                    sessionStorage.setItem("deviceIsOpen", deviceIsOpen);
                    $("#openDevice").attr('disabled',"disabled");
                    $("#closeDevice").removeAttr('disabled',"disabled");
                    $("#checkin").removeAttr('disabled',"disabled");
                }
                layer.close(loadLayer)
            }
        };
        //异步打开串口
        $.ajax(options);
    });

    /*关闭设备*/
    $("#closeDevice").click(function () {
        openLoadLayer('正在关闭设备......');
        var options = {
            type: 'get',
            url: 'opt/port/close',
            success:function (result) {
                addMsg(result.msg)
                if (result.code === 0){
                    sessionStorage.removeItem("deviceIsOpen");
                    $("#openDevice").removeAttr('disabled',"disabled");
                    $("#closeDevice").attr('disabled',"disabled");
                    $("#checkin").attr('disabled',"disabled");
                }
                layer.close(loadLayer)
            }
        };
        //异步关闭串口
        $.ajax(options);
    });

    /*查询学生*/
    $("#searchByStudentId").click(function () {
        student = null;
        $("#searchTip > span").remove("span");
        var studentId = $("#studentId").val();
        if(studentId == null || studentId === ''){
            $("#searchTip").append('<span>请先输入学号！</span>')
            return;
        }
        $.ajax({
            type: 'get',
            url: 'http://localhost/api/finger/student/'+studentId,
            success: function (result) {
                if (result.code === 0){
                    //查询成功
                    student= result.data;
                    $(".studentId > span").remove();
                    $(".studentName > span").remove();
                    $(".studentGender > span").remove();
                    $(".fingerprint > span").remove();
                    $(".studentId").append('<span>'+student.id+'</span>');
                    $(".studentName").append('<span>'+student.name+'</span>');
                    $(".studentGender").append('<span>'+(student.gender === 0 ? "男" : "女")+'</span>');
                    $(".fingerprint").append('<span>'+(student.fingerPrint != null ? "已录入" : "未录入")+'</span>');
                }else{
                    //查询失败
                    $("#searchTip").append('<span>查询失败！</span>')
                    $(".studentId").remove("span");
                    $(".studentName").remove("span");
                    $(".studentGender").remove("span");
                    $(".fingerprint").remove("span");
                }
            },
            error:function (result) {
                console.log(result.msg);
            }
        });
    });

    /*指纹采集*/
    $("#getImage").click(function () {
        $("#searchTip > span").remove();
        if (student == null){
            $("#searchTip").append('<span>请至少选择一位同学！</span>')
            return ;
        }
        openLoadLayer('指纹采集中，手指请不要离开采集器..')
        //获取指纹图像
        $.ajax({
            type: 'get',
            url: 'opt/getImage',
            success : function (result) {
                addMsg(result.msg)
                layer.close(loadLayer)
                if (result.code === 0){
                    //指纹图像采集成功
                    getImageFlag = true;
                    var a = document.createElement('a');
                    a.href = "images/fingerprint.bmp";
                    a.download = student.id + ".bmp";
                    a.click();
                }else{
                    getImageFlag = false;
                }
            }
        });
    });

    /*指纹信息上传*/
    $("#uploadFinger").click(function () {
        var pId = -1;
        if (student != null && getImageFlag){
            openLoadLayer("正在上传指纹信息.....")
            if (student.fingerPrint != null){
                pId = student.fingerPrint.flashId;
            }
            //上传指纹模板到指纹采集模块
            $.ajax({
                type: 'get',
                url: 'opt/storeModel',
                data: {"pId" : pId},
                success: function (result){
                    addMsg(result.msg);
                    if (result.code === 0){
                        var flashId = result.flashId;
                        //上传学生指纹信息
                        uploadStudentInfo(student.id,flashId)
                    }else {
                        layer.close(loadLayer)
                    }
                }
            })
        }else {
            layer.close(loadLayer)
            layer.msg("指纹信息上传失败！")
        }
    });

    /*指纹验证*/
    $("#checkin").click(function () {
        openLoadLayer('指纹采集中，手指请不要离开采集器..')
        var searchOption = {
            type: 'get',
            url: 'opt/searchModel',
            success: function (result) {
                if (result.code === 0){
                    //上传签到信息
                    var checkinId = $("#checkinList").val();
                    var modelNum = result.modelNum;
                    $.ajax({
                        type: 'get',
                        url: 'http://localhost/api/finger/checkin/'+checkinId+'/finger/'+modelNum,
                        success:function (result) {
                            //显示签到成功
                            if (result.code === 0){
                                var data = result.data;
                                layer.open({
                                    title: '签到'
                                    ,content: data.name+'同学，成功签到！'
                                });
                            }else {
                                layer.msg(result.msg)
                            }
                        }
                    })
                }else {
                    addMsg(result.msg)
                }
                layer.close(loadLayer)
            }
        }
        //获取指纹图像
        var getImageOptions = {
            type: 'get',
            url: 'opt/getImage',
            success : function (result) {
                if (result.code === 0){
                    $.ajax(searchOption);
                }else{
                    addMsg(result.msg)
                    layer.close(loadLayer)
                }
            }
        };
        //获取指纹图像
        $.ajax(getImageOptions);
    });
})

function uploadStudentInfo(studentId, flashId) {
    //封装上传信息：学生ID，FlashID,指纹图像
    var studentInfo = new FormData();
    var imageFile = $("#uploadImage")[0].files[0];
    studentInfo.append("studentId", studentId);
    studentInfo.append("flashId", flashId);
    studentInfo.append("imageFile",imageFile);
    $.ajax({
        type : "post",
        url : "http://localhost/api/finger/fingerprint/upload",
        data : studentInfo,
        processData : false,
        contentType : false,
        success : function (result) {
            addMsg(result.msg)
            layer.close(loadLayer)
        }
    })
}